package com.haiwen.controller;
import com.haiwen.utils.UserContext;
import com.haiwen.vo.responseData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Properties;

@RestController
public class MailingController {
    @Autowired
    private JavaMailSender javaMailSender;//在spring中配置的邮件发送的bean
    @PostMapping(value = "/mall.do")
    public responseData mall(String mailbox,
                             HttpServletRequest request){
        HttpSession session = request.getSession();
        MimeMessage mMessage=javaMailSender.createMimeMessage();//创建邮件对象
        MimeMessageHelper mMessageHelper;
        Properties prop = new Properties();
        String from;
        int VerificationCode=(int)((Math.random()*9+1)*100000);
        if (mailbox.equals("")){
            return new responseData(500,"请输入邮箱地址");
        }
        //从配置文件中拿到发件人邮箱地址
        try {
            prop.load(this.getClass().getResourceAsStream("/conf/email.properties"));
            from = prop.get("mail.smtp.username")+"";
            mMessageHelper=new MimeMessageHelper(mMessage,true);
            mMessageHelper.setFrom(from);//发件人邮箱
            mMessageHelper.setTo(mailbox);//收件人邮箱
            mMessageHelper.setSubject("注册验证码");//邮件的主题
            mMessageHelper.setText("<p>欢迎注册</p><br/>" +
                    "<h1>本次验证码为:"+VerificationCode+"</h1>",true);//邮件的文本内容，true表示文本以html格式打开
            session.setAttribute(UserContext.VERIFICATION_CODE,VerificationCode);
            System.out.println(session.getAttribute(UserContext.VERIFICATION_CODE));
            session.setMaxInactiveInterval(60*2);
            javaMailSender.send(mMessage);//发送邮件
            return new responseData(200,"发送成功");
        } catch (Exception e) {
            return new responseData(500,"发送失败");
        }

    }
}
